package org.example.aidemo.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.aidemo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 获取请求路径（不包含上下文路径）
        String requestPath = request.getRequestURI().substring(request.getContextPath().length());
        // 标准化路径（移除可能的尾部斜杠）
        if (requestPath.endsWith("/")) {
            requestPath = requestPath.substring(0, requestPath.length() - 1);
        }

        // 添加调试日志
        System.out.println("处理请求路径: " + requestPath);
        System.out.println("收到的Authorization头部: " + request.getHeader("Authorization"));

        // 对于登录请求和错误路径，直接放行
        if ("/auth/login".equals(requestPath) || "/error".equals(requestPath)) {
            System.out.println("路径无需认证，直接放行");
            chain.doFilter(request, response);
            return;
        }

        String jwt = getJwtFromRequest(request);
        System.out.println("提取的JWT令牌: " + jwt);

        if (StringUtils.hasText(jwt)) {
            try {
                String token = jwtUtils.getUsernameFromToken(jwt);
                // 从 Redis 中获取存储的 JWT
                String storedJwt = redisTemplate.opsForValue().get("jwt:" + token);
                // 验证令牌有效性及是否存在于 Redis 中
                boolean isValid = jwtUtils.validateToken(jwt) && jwt.equals(storedJwt);

                if (isValid) {
                    String username = jwtUtils.getUsernameFromToken(jwt);
                    System.out.println("从令牌中提取的用户名: " + username);

                    // 从数据库或缓存中加载用户详细信息
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    System.out.println("加载的用户信息: " + userDetails.getUsername() + ", 角色: " + userDetails.getAuthorities());

                    // 创建Authentication对象
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    // 将Authentication对象存入Security上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    System.out.println("认证信息已设置到Security上下文");
                }
            } catch (Exception e) {
                System.out.println("JWT处理异常: " + e.getMessage());
                e.printStackTrace();
            }
        }

        chain.doFilter(request, response); // 继续执行过滤器链
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            // 如果以"Bearer "开头，则去掉前缀
            if (bearerToken.startsWith("Bearer ")) {
                return bearerToken.substring(7);
            }
            // 否则直接返回令牌
            return bearerToken;
        }
        return null;
    }
}